from flask import render_template, redirect, g, request, jsonify, current_app, session, abort
from flask_sqlalchemy import Pagination

from info import db, constants
from info.models import Category, News
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route('/info')
@user_login_data
def get_user_info():
    """
    获取用户信息
    1. 获取到当前登录的用户模型
    2. 返回模型中指定内容
    :return:
    """

    user = g.user
    if not user:
        # 用户未登录，重定向到主页
        return redirect('/')

    data = {
        "user_info": user.to_dict(),
    }
    # 渲染模板
    return render_template("news/user.html", data=data)


@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    user = g.user

    if request.method == 'GET':
        data = {
            "user_info": user.to_dict(),
        }
        return render_template("news/user_base_info.html", data=data)

    # 2. 获取到传入参数
    data_dict = request.json
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")
    signature = data_dict.get("signature")
    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    print(gender)
    if gender not in (['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 更新并保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user_info": user.to_dict()})

    # 1.获取上传的文件
    try:
        file = request.files.get('avatar')  # 获取文件对象
        avatar_file = file.read()  # 读取数据
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2.保存到七牛云
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片出错")
    # 3把文件名字保存到数据库
    user.avatar_url = url
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    # 4.返回响应

    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    """修改密码"""
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 1获取参数
    json_data = request.json
    old_password = json_data.get('old_password')
    new_password = json_data.get('new_password')

    # 2判断是否为空g
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3获取当前用户 验证原密码
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 4更新密码
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    """收藏页面显示"""
    # 1获取参数
    # 当前页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 获取数据
    user = g.user
    collections = []  # 存放新闻对象的列表
    current_page = 1  # 当前页
    total_page = 1  # 总页数

    try:
        pagination = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        collections = pagination.items
        current_page = pagination.page
        total_page = pagination.pages
    except Exception as e:
        current_app.logger.error(e)

    collection_dict_li = []
    # 转为字段数据存到列表里
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    print('total_page', total_page)
    print('current_page', current_page)
    # 所有数据
    data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_li}

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/news_release', methods=["POST", "GET"])
@user_login_data
def news_release():
    # 查询所有的分类

    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 转为字典数据
        categories_dict_li = []
        for category in categories:
            categories_dict_li.append(category.to_dict())

        # 删除 ‘最新’ 这一条数据
        categories_dict_li.pop(0)

        data = {'categories': categories_dict_li}
        # 返回内容
        return render_template('news/user_news_release.html', data=data)

    # 1获取数据
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    content = request.form.get('content')
    # 图片 index_image 是个文件 对象
    index_image = request.files.get('index_image')

    # 来源
    source = '个人发布'

    print('title', title)
    print('category_id', category_id)
    print('digest', digest)
    print('index_image', index_image)
    print('title', title)
    print('content', content)

    # 校验
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    # 读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='图片读取有误')

    # 上传图片
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='d上传图片错误')
    print('key', key)
    # 保存一条新的新闻
    news = News()

    news.title = title
    news.digest = digest
    news.source = source
    news.content = content

    # 新闻的图片存完整路径  因为todict里转换里没有拼接前缀
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    """发布的新闻列表"""
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 登录的用户
    user = g.user

    follows = []  # 存放当前页数据对象
    current_page = 1  # 获取当前页
    total_page = 1  # 获取总页数
    try:
        # 分页获取
        pagination = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = pagination.items
        # 获取当前页
        current_page = pagination.page
        # 获取总页数
        total_page = pagination.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []  # 存放最后的字典数据

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)


from info.models import User


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    # 当前用户信息
    user = g.user

    # 获取传入的用户id
    user_id = request.args.get('id')

    # id没有传
    if not user_id:
        abort(404)

    other = None
    try:
        # 查询用户
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    # 判断用户是否存在
    if not other:
        abort(404)

    is_followed = False
    if user:
        # 判断当前登录的用户有没有关注other
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data = {
        'other_info': other.to_dict(),
        'is_followed': is_followed,
        'user_info': user.to_dict() if user else None
    }
    return render_template('news/other.html', data=data)


@profile_blu.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)  # 第几页数据
    user_id = request.args.get("user_id")  # 哪一个用户的
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        # 查询当前用户
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, 1, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []
    # 获取新闻的字典数据
    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
